package cn.le.aopAnnotationDataSource.aop;

import cn.le.aopAnnotationDataSource.annotation.DataSource;
import cn.le.aopAnnotationDataSource.jdbc.JdbcContextHolder;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

/**
 * Created by admin on 2017/3/28.
 * aop解析@dataSource注解,实现动态数据源切换
 */
public class DataSourceChoose implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {

        System.out.println(o.toString());
        System.out.println(method.getName());
        if (method.isAnnotationPresent(DataSource.class))
        {
            DataSource data = method.getAnnotation(DataSource.class);
            JdbcContextHolder.clearJdbcType();
            JdbcContextHolder.setJdbcType(data.value().getName());
            System.out.println(data.value().getName());
        }
    }

    //不使用实现MethodBeforeAdvice接口的方式可以使用下面的代码,单使用下面的代码aop的切入类必须采用接口的方式
    //方法执行前
    /*public void before(JoinPoint point) throws NoSuchMethodException, ClassNotFoundException {

        Object target = point.getTarget();
        String method = point.getSignature().getName();
        System.out.println(method);
        Class<?>[] classz = target.getClass().getInterfaces();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
                .getMethod().getParameterTypes();
        try {
            Method m = classz[0].getMethod(method, parameterTypes);
            if (m != null && m.isAnnotationPresent(DataSource.class)) {
                DataSource data = m.getAnnotation(DataSource.class);
                JdbcContextHolder.clearJdbcType();
                JdbcContextHolder.setJdbcType(data.value().getName());
                System.out.println(data.value().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }*/
}
